using System;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Drawing;

namespace HomeWork06
{
    public class FileBrowser : Form
    {
        private MenuStrip menuStrip;
        private ToolStrip toolStrip;
        private SplitContainer splitContainer;
        private TreeView folderTreeView;
        private ListView fileListView;
        private ImageList imageList;

        public FileBrowser()
        {
            InitializeComponents();
            InitializeImageList();
            LoadDrives();
        }

        private void InitializeComponents()
        {
            // 设置窗体基本属性
            this.Text = "文件浏览器";
            this.Size = new Size(800, 600);

            // 初始化菜单栏
            menuStrip = new MenuStrip();
            ToolStripMenuItem fileMenu = new ToolStripMenuItem("文件(&F)");
            fileMenu.DropDownItems.Add("退出(&X)", null, (s, e) => Application.Exit());
            menuStrip.Items.Add(fileMenu);
            this.Controls.Add(menuStrip);

            // 初始化工具栏
            toolStrip = new ToolStrip();
            toolStrip.Items.Add("刷新", null, (s, e) => RefreshCurrentView());
            this.Controls.Add(toolStrip);

            // 初始化分隔容器
            splitContainer = new SplitContainer();
            splitContainer.Dock = DockStyle.Fill;
            splitContainer.SplitterDistance = 250;

            // 初始化树形视图
            folderTreeView = new TreeView();
            folderTreeView.Dock = DockStyle.Fill;
            folderTreeView.AfterSelect += FolderTreeView_AfterSelect;
            splitContainer.Panel1.Controls.Add(folderTreeView);

            // 初始化文件列表视图
            fileListView = new ListView();
            fileListView.Dock = DockStyle.Fill;
            fileListView.View = View.Details;
            fileListView.Columns.Add("名称", 200);
            fileListView.Columns.Add("类型", 100);
            fileListView.Columns.Add("大小", 100);
            fileListView.Columns.Add("修改日期", 150);
            fileListView.DoubleClick += FileListView_DoubleClick;
            splitContainer.Panel2.Controls.Add(fileListView);

            // 设置控件布局
            this.Controls.Add(splitContainer);
            menuStrip.SendToBack();
            toolStrip.SendToBack();
        }

        private void InitializeImageList()
        {
            imageList = new ImageList();
            imageList.Images.Add("folder", SystemIcons.Folder.ToBitmap());
            imageList.Images.Add("file", SystemIcons.WinLogo.ToBitmap());
            
            folderTreeView.ImageList = imageList;
            fileListView.SmallImageList = imageList;
        }

        private void LoadDrives()
        {
            folderTreeView.Nodes.Clear();
            DriveInfo[] drives = DriveInfo.GetDrives();

            foreach (DriveInfo drive in drives)
            {
                if (drive.IsReady)
                {
                    TreeNode driveNode = new TreeNode(drive.Name);
                    driveNode.Tag = drive.RootDirectory.FullName;
                    driveNode.ImageKey = "folder";
                    driveNode.SelectedImageKey = "folder";
                    folderTreeView.Nodes.Add(driveNode);
                    LoadSubDirectories(driveNode);
                }
            }
        }

        private void LoadSubDirectories(TreeNode node)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(node.Tag.ToString());
                foreach (DirectoryInfo subDir in dir.GetDirectories())
                {
                    TreeNode subNode = new TreeNode(subDir.Name);
                    subNode.Tag = subDir.FullName;
                    subNode.ImageKey = "folder";
                    subNode.SelectedImageKey = "folder";
                    node.Nodes.Add(subNode);
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 忽略访问被拒绝的目录
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载目录时出错: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FolderTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            DisplayFolderContents(e.Node.Tag.ToString());
        }

        private void DisplayFolderContents(string path)
        {
            fileListView.Items.Clear();
            try
            {
                DirectoryInfo dir = new DirectoryInfo(path);

                // 添加子目录
                foreach (DirectoryInfo subDir in dir.GetDirectories())
                {
                    ListViewItem item = new ListViewItem(subDir.Name, "folder");
                    item.SubItems.Add("文件夹");
                    item.SubItems.Add("");
                    item.SubItems.Add(subDir.LastWriteTime.ToString());
                    item.Tag = subDir.FullName;
                    fileListView.Items.Add(item);
                }

                // 添加文件
                foreach (FileInfo file in dir.GetFiles())
                {
                    ListViewItem item = new ListViewItem(file.Name, "file");
                    item.SubItems.Add(file.Extension);
                    item.SubItems.Add(FormatFileSize(file.Length));
                    item.SubItems.Add(file.LastWriteTime.ToString());
                    item.Tag = file.FullName;
                    fileListView.Items.Add(item);
                }
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("访问被拒绝", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"显示目录内容时出错: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string FormatFileSize(long bytes)
        {
            string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
            int counter = 0;
            decimal number = bytes;
            while (Math.Round(number / 1024) >= 1)
            {
                number = number / 1024;
                counter++;
            }
            return string.Format("{0:n1} {1}", number, suffixes[counter]);
        }

        private void FileListView_DoubleClick(object sender, EventArgs e)
        {
            if (fileListView.SelectedItems.Count > 0)
            {
                string path = fileListView.SelectedItems[0].Tag.ToString();
                if (Path.GetExtension(path).ToLower() == ".xml")
                {
                    ShowXmlContent(path);
                }
            }
        }

        private void ShowXmlContent(string xmlPath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlPath);

                Form xmlForm = new Form();
                xmlForm.Text = "XML内容 - " + Path.GetFileName(xmlPath);
                xmlForm.Size = new Size(600, 400);

                TreeView xmlTree = new TreeView();
                xmlTree.Dock = DockStyle.Fill;
                xmlForm.Controls.Add(xmlTree);

                TreeNode rootNode = new TreeNode(doc.DocumentElement.Name);
                xmlTree.Nodes.Add(rootNode);
                AddXmlNode(doc.DocumentElement, rootNode);

                xmlForm.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"解析XML文件时出错: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AddXmlNode(XmlNode xmlNode, TreeNode treeNode)
        {
            // 添加属性
            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attr in xmlNode.Attributes)
                {
                    TreeNode attrNode = new TreeNode($"@{attr.Name} = {attr.Value}");
                    treeNode.Nodes.Add(attrNode);
                }
            }

            // 添加子节点
            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                TreeNode childTreeNode;
                if (childNode is XmlText)
                {
                    string text = childNode.Value.Trim();
                    if (!string.IsNullOrEmpty(text))
                    {
                        childTreeNode = new TreeNode($"Text: {text}");
                        treeNode.Nodes.Add(childTreeNode);
                    }
                }
                else
                {
                    childTreeNode = new TreeNode(childNode.Name);
                    treeNode.Nodes.Add(childTreeNode);
                    AddXmlNode(childNode, childTreeNode);
                }
            }
        }

        private void RefreshCurrentView()
        {
            if (folderTreeView.SelectedNode != null)
            {
                DisplayFolderContents(folderTreeView.SelectedNode.Tag.ToString());
            }
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FileBrowser());
        }
    }
}